package com.gqr.threadobjectclasscommonmethods;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:Wait
 * author:guqingrong
 * Date:2024-04-21 15:34
 * Description:展示wait和notify的基本用法
 * 1.研究代码的执行顺序
 * 2. 证明wait是释放锁的
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class Wait {
    public static Object object = new Object();

    static class Thread1 extends Thread{
        @Override
        public void run() {
            synchronized (object){
                System.out.println("线程"+Thread.currentThread().getName()+"开始执行了");

                try {
                    // 线程1 进入synchronized
                    // 执行到这行 wait 会释放锁
                    // 释放锁之后  线程2进入到  synchronized
                    // 线程2 在进入到 synchronized之后 调用notify 释放了锁
                    // 线程1 继续执行 wait后面的内容
                    object.wait();
                    System.out.println("线程"+Thread.currentThread().getName()+"执行await后面的代码");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程"+Thread.currentThread().getName()+"获取到了锁.");
            }
        }
    }

    static class Thread2 extends Thread{
        @Override
        public void run() {
            synchronized (object){
                object.notify();
                System.out.println("线程"+Thread.currentThread().getName()+"调用了notify()");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread1.start();
        Thread.sleep(200);
        thread2.start();
    }

}
